/*
* @moudule:@/views/home/incomeAnalysis_total
* @author:zengfx
* @date:2020-10-19
*/

<template>
  <div class="total_container">
    <header>
      <p>区域收入完成月报</p>
      <!-- {{titleArea}} -->
      <el-button size="mini" @click="handle_back">返回</el-button>
    </header>
    <main>
      <el-form :inline="true" :model="form" class="main_searchBar">
        <!-- <el-form-item label="收入年度:">
          <el-select size="mini" v-model="formInline.year" clearable>
            <el-option
              v-for="(item, index) in yearList"
              :key="index"
              :label="item.label"
              value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item label="区域:">
          <dx-cascader :area_id.sync="form.areaId" ref="cascader" />
        </el-form-item>
        <el-form-item label="收入指标:">
          <el-select @change="handleCode" size="mini" v-model="form.code" clearable>
            <el-option label="全部" value="全部"></el-option>
            <el-option v-for="(item, index) in codeList" :key="index" :label="item.indexName" :value="item.indexCode"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="客户群:">
          <el-select size="mini" v-model="form.customer" clearable>
            <el-option v-for="(item, index) in customerList" :key="index" :label="item.indexName" :value="item.indexCode"></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item label="存增量" v-if="showStorage">
          <el-select size="mini" v-model="form.storageCode" clearable>
            <el-option v-for="(item, index) in storageCodeList" :key="index" :label="item.indexName" :value="item.indexCode"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" id="search_btn" @click="handle_search">查询</el-button>
          <el-button size="mini" id="export_btn" @click="handle_export">导出</el-button>
        </el-form-item>
      </el-form>
      <div class="main_navBar">
        <!-- <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item
            v-for="(nav, navIndex) in navList"
            :key="navIndex"
            :to="{ path: nav.toLink }"
            >{{ nav.label }}</el-breadcrumb-item
          >
        </el-breadcrumb>-->

        <div class="area">
          <div class="it" v-for="(item, index) in areaList" :key="index" @click="changeArea(index)">
            <span class="td">{{ item.label }}</span>
            <span>-></span>
          </div>
        </div>
        <span style="flex:1; text-align: right;padding-right: 15px;">单位:万元</span>
        <!-- <el-checkbox v-model="checked">环比</el-checkbox> -->
      </div>
      <div class="tableBox">
        <el-table size="mini" id="table1" stripe height="65vh" :data="tableData1" v-loading="tableLoading" border style="width: 100%">
          <el-table-column :label="titleArea" fixed="left" width="160">
            <template slot-scope="scope">
              <span class="hover" @click="goArea(scope.row, scope.$index)" v-text="scope.row.areaName || scope.row.area_NAME"></span>
            </template>
          </el-table-column>
          <!--  -->
          <template v-if="titleArea == '区域'">
            <!-- <el-table-column
            min-width="120"
            align="center"
            v-for="(item, index) in titleList"
            :key="index"
            :label="index == 0 ? 'T0' : (index == titleList.length - 1 ) ? '累计同比' : item"
          >
            <template slot-scope="scope">
              <span class="num" style="cursor: pointer" @click="handle_level(scope.row)">{{ scope.row["indexValue" + index] }}</span>
            </template>
          </el-table-column>-->
            <!-- <el-table-column min-width="160" align="center" label="合计" prop="value14"></el-table-column> -->
            <el-table-column min-width="120" align="center" v-for="(item, index) in titleList" :key="index" :label="item.name">
              <template slot-scope="scope">
                <span class="num" style="cursor: pointer" @click="handle_level(scope.row)">{{scope.row[item.data]}}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column min-width="120" align="center" label="累计同比" prop="value13"></el-table-column> -->
          </template>
          <template v-if="titleArea == '来源'">
            <el-table-column min-width="120" align="center" v-for="(item, index) in titleList" :key="index" :label="item.name">
              <template slot-scope="scope">
                <span class="num" style="cursor: pointer" @click="handle_level(scope.row)">{{ scope.row[item.data] }}</span>
              </template>
            </el-table-column>
          </template>
        </el-table>

      </div>

    </main>
  </div>
</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
import { $budgetAPI } from "@/api";
import { getCookie } from "@/common/js/cookie";
import {
  setSessionStorage,
  getSessionStorage,
  removeSessionStorage,
} from "@/common/js/storage";
export default {
  data() {
    return {
      form: {
        year: "",
        areaId: "",
        code: "YS10000",
        customer: "",
        storageCode: "",
      },
      yearList: [],
      codeList: [],
      customerList: [],
      storageCodeList: [],
      navList: [
        {
          label: "嘉兴分公司",
          toLink: "/budget/incomeAnalysis_total",
        },
        {
          label: "嘉善分局",
          toLink: "/budget/incomeAnalysis_total",
        },
      ],
      checked: false,
      tableData1: [],
      tableData2: [],
      titleList: [],
      codeList: [],
      tableLoading: true,
      areaIds: [],
      areaNames: [],
      areaList: [],
      showStorage: "",
      type: "1",
      titleArea: "区域",
    };
  },
  mounted() {
    var that = this;

    that.accountInfo = JSON.parse(getSessionStorage("accountInfo"));
    that.form.areaId = that.accountInfo.areaId;
    that.form.areaName = that.accountInfo.areaName;
    // $budgetAPI.getinitCompany({}, res => {
    //   console.log(res.content);
    //   that.form.areaId = res.content.areaId;
    //   debugger

    // }, err => {
    //   console.log(err);
    // })

    that.initData();
  },
  methods: {
    afterTitle(index) {
      return "value" + index;
    },
    handle_search() {
      var that = this;

      var obj = {
        areaId: that.form.areaId,
        indexCode: that.form.code,
        custerCode: that.form.customer,
        storageCode: that.form.storageCode,
        showHb: that.checked ? "1" : "0",
        type: that.type,
      };
      that.titleArea = "区域";
      that.getData(obj);
    },
    handle_export() {
      var xlsxParam = {
        raw: true,
      };
      // 判断要导出的节点中是否有fixed的表格，如果有，转换excel时先将该dom移除，然后append回去，
      var fix = document.querySelector(".el-table__fixed");
      var wb;
      if (fix) {
        wb = XLSX.utils.table_to_book(
          document.querySelector("#table1").removeChild(fix)
        );
        document.querySelector("#table1").appendChild(fix);
      } else {
        wb = XLSX.utils.table_to_book(
          document.querySelector("#table1"),
          xlsxParam
        );
      }
      let wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], {
            type: 'application/octet-stream;charset=utf-8"',
          }),
          "区域收入完成月报.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbOut);
      }
      return wbout;
    },
    handle_back() {
      this.$router.go(-1);
    },
    async initData() {
      var that = this,
        code,
        customer,
        storage,
        data,
        obj = {};

      code = await that.getCodeList();
      customer = await that.getCustomerGroup();

      that.codeList = code;
      that.customerList = customer;

      //   that.form.code = code[0].indexCode;
      that.form.customer = "";

      obj = {
        areaId: that.form.areaId,
        indexCode: that.form.code,
        // indexCode: code[0].indexCode.toString(),
        custerCode: "",
        storageCode: "",
        showHb: that.checked ? "1" : "0",
        type: that.type,
      };
      that.titleArea = "区域";
      that.getData(obj);
      // that.getStorage(code[0].indexCode);
    },
    getData(obj) {
      var that = this,
        data = "";

      that.tableLoading = true;
      $budgetAPI.getIncomeViewData(
        {
          areaId: obj.areaId,
          indexCode: obj.indexCode,
          custerCode: obj.custerCode,
          storageCode: obj.storageCode,
          showHb: obj.showHb,
          type: obj.type,
        },
        (res) => {
          if (res.code == 0) {
            data = res.content.data;

            // 来源去掉T0和环比
            if (that.titleArea == "来源") {
              data.map((it) => {
                it.dataList.map((item, i) => {
                  if (i != 0 && i != it.dataList.length - 1) {
                    it["indexValue" + (i - 1)] = that.checked
                      ? item.hbValue
                      : item.indexValue;
                    it["isClick"] = item.isClick;
                  }
                });
              });
              that.titleListCopy = res.content.titles;
              // console.log(res.content.titles)
              that.titleListCopy.map((item, index) => {
                if (item == "T0") {
                  that.titleListCopy.splice(index, 1);
                }
                if (item == "累计同比") {
                  that.titleListCopy.splice(index, 1);
                }
              });
              that.titleList = that.titleListCopy;
              // console.log(that.titleListCopy,'11')
              that.tableData1 = data;
              that.tableLoading = false;
              that.areaIds = res.content.areaIds.split(",");
              that.areaNames = res.content.areaNames.split("->");
              that.areaList = [];
              that.areaIds.map((it, i) => {
                var o = {
                  label: that.areaNames[i],
                  value: that.areaIds[i],
                };
                that.areaList.push(o);
              });
            } else {
              // data.map(it => {
              //     it.dataList.map((item, i) => {
              //         // it['indexValue' + i] = that.checked ? item.hbValue : item.indexValue;
              //         it['isClick'] = item.isClick;
              //     });
              // });
              that.titleList = res.content.titles;
              // console.log( that.titleList)
              that.tableData1 = data;
              that.tableLoading = false;
              that.areaIds = res.content.areaIds.split(",");
              that.areaNames = res.content.areaNames.split("->");
              that.areaList = [];
              that.areaIds.map((it, i) => {
                var o = {
                  label: that.areaNames[i],
                  value: that.areaIds[i],
                };
                that.areaList.push(o);
              });
            }
          }
        },
        (err) => {
          console.log(err);
        }
      );
    },
    getCodeList() {
      var that = this;

      return new Promise((resolve) => {
        $budgetAPI.getIncomeIndexCodeList(
          {},
          (res) => {
            if (res && res.code == 0) {
              resolve(res.content);
            }
          },
          (err) => {}
        );
      });
    },
    getCustomerGroup() {
      var that = this;

      return new Promise((resolve) => {
        $budgetAPI.getCustomerGroup(
          {},
          (res) => {
            if (res && res.code == 0) {
              resolve(res.content);
            }
          },
          (err) => {}
        );
      });
    },
    handleCode(val) {
      var that = this;

      // that.getStorage(val);
    },
    getStorage(code) {
      var that = this;

      $budgetAPI.getStorage(
        {
          indexCode: code,
        },
        (res) => {
          if (res && res.code == 0) {
            that.storageCodeList = res.content;
            that.showStorage =
              (that.storageCodeList && that.storageCodeList.length) || "";
          }
        },
        (err) => {}
      );
    },
    handle_level(obj) {
      var that = this;
      // 来源时跳转波动topo
      if (that.titleArea == "来源") {
        that.$router.push({
          path: "/budget/TOPO",
          query: {
            areaId: that.form.areaId,
            customer: that.form.customer,
            code: that.form.code,
          },
        });
        return;
      }
      let params = {
        areaId: obj.areaId,
        indexCode: that.form.code,
        custerCode: that.form.customer,
        storageCode: that.form.storageCode,
        showHb: that.checked ? "1" : "0",
        type: "2",
      };
      // if (obj.isClick == 0) {
      // that.titleArea = "来源";
      that.getData(params);
      // }
    },
    changeArea(val) {
      var that = this;

      var obj = {
        areaId: that.areaList[val].value,
        indexCode: that.form.code,
        custerCode: that.form.customer,
        storageCode: that.form.storageCode,
        showHb: that.checked ? "1" : "0",
        type: that.type,
      };
      that.form.areaId = that.areaList[val].value;
      that.titleArea = "区域";
      that.getData(obj);
    },
    goArea(val, index) {
      var that = this;

      var obj = {
        areaId: val.areaId,
        indexCode: that.form.code,
        custerCode: that.form.customer,
        storageCode: that.form.storageCode,
        showHb: that.checked ? "1" : "0",
        type: that.type,
      };
      // if (index == 0) {
      //   return false;
      // }
      if (val.leftClick == 0) {
        that.titleArea = "区域";
        that.form.areaId = val.areaId;
        that.getData(obj);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.total_container {
  width: 100%;
  height: 100%;
  .hover {
    cursor: pointer;
    color: #3456dc;
  }
  .num {
    &:hover {
      color: #3456dc;
    }
  }
  & > header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #eaeaea;
    height: 40px;
    margin: 0 -20px;
    padding: 0 20px;
    & > p {
      font-weight: bold;
      font-size: 15px;
    }
  }
  & > main {
    padding: 0 10px 10px;
    /deep/ .el-table__fixed-body-wrapper {
      top: 37px !important;
    }
    .main_searchBar {
      border-bottom: 1px solid #d6d9e5;
      /deep/ .el-form-item {
        margin: 6px 10px 6px 0;
      }
      button {
        color: #fff;
        border: none;
        outline: none;
        &:hover {
          opacity: 0.8;
        }
      }
      #search_btn {
        background-color: #2a90de;
      }
      #export_btn {
        background-color: #2cd531;
      }
    }
    .main_navBar {
      padding: 10px 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .area {
        text-align: left;
        display: flex;
        .it {
          cursor: pointer;
          font-size: 14px;
          display: inline-block;
          .td {
            font-weight: bold;
          }
          &:last-child {
            span {
              &:last-child {
                display: none;
              }
            }
          }
        }
      }
    }
  }
}
</style>
